//
//  GLSceneViewController.m
//  LMPhotoVideoSDK
//
//  Created by Aimar on 16/7/7.
//  Copyright © 2016年 魁钺会. All rights reserved.
//

#import "GLSceneViewController.h"
#import "OpenGLCoreDefine.h"
#import "GLTextureShader.h"
#import "GLTexture.h"
#import "GLDrawable.h"

@interface GLSceneViewController ()

@property (nonatomic, readonly, strong)NSMutableArray<GLDrawable*>*      drawables;

@property (nonatomic, strong)GLCanvas*                                      canvas;

@end

@implementation GLSceneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    EAGLContext* context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    GLKView* glView = (GLKView *)self.view;
    glView.context = context;
    glView.contentScaleFactor = 1;
    self.preferredFramesPerSecond = 60;
    [EAGLContext setCurrentContext:context];
    
    self.view.backgroundColor = [UIColor blackColor];
    self.frame = glView.frame;
    
    _drawables = [NSMutableArray arrayWithCapacity:10];
    _canvas = [[GLCanvas alloc] init];
    
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    CGFloat fovy = 45.0;
    CGFloat offset = (width / 2) / tanf(GLKMathDegreesToRadians (fovy) / 2.0);
    mat4 camera = mat4::LookAt(width / 2, -height / 2, offset, width / 2, -height / 2, 0, 0, 1, 0);
    mat4 projection = mat4::Perspective(fovy, width / height, offset - 0.1, 10000);
    projection = camera * projection;
    [self.canvas setProjection:projection];
}

- (void)onGLViewUpdate {
    
}

- (void)onGLViewRender {
    
}

- (void)update {
    
    [self onGLViewUpdate];
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
    [self draw:self.canvas];
    [self onGLViewRender];}

- (void)draw:(GLCanvas*)canvas {
    glClearColor(0.8, 0.8, 0.8, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    
    glViewport(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
    
    NSInteger count = [self getDrawableCount];
    for (NSInteger i=0; i<count; ++i) {
        [self.canvas save];
        [[self getDrawableAt:i] draw:canvas];
        [self.canvas restore];
    }
}

#pragma mark GLDrawableGroup
- (void)addDrawable:(GLDrawable*)drawable {
    [self.drawables addObject:drawable];
}

- (void)addDrawable:(GLDrawable*)drawable at:(NSInteger)index {
    [self.drawables insertObject:drawable atIndex:index];
}

- (NSInteger)getDrawableCount {
    return self.drawables.count;
}

- (NSInteger)indexOfDrawable:(GLDrawable*)drawable {
    return [self.drawables indexOfObject:drawable];
}

- (GLDrawable*)getDrawableAt:(NSInteger)index {
    return [self.drawables objectAtIndex:index];
}

- (void)removeDrawable:(GLDrawable*)drawable {
    [self.drawables removeObject:drawable];
}

- (void)removeDrawableAt:(NSInteger)index {
    [self.drawables removeObjectAtIndex:index];
}

- (void)removeAllDrawables {
    [self.drawables removeAllObjects];
}

@end
